package com.hanhai.material.device.service.impl;

import com.hanhai.material.common.result.Result;
import com.hanhai.material.device.entity.SysProductRecordDetentionRecord;
import com.hanhai.material.device.entity.SysProductRecordInto;
import com.hanhai.material.device.service.AsyncService;
import com.hanhai.material.device.service.SysProductRecordDetentionRecordService;
import com.hanhai.material.device.service.SysProductRecordDetentionService;
import com.hanhai.material.device.service.SysProductRecordIntoService;
import com.hanhai.material.device.utils.kingdee.ProductReceiptUtil;
import com.hanhai.material.device.utils.kingdee.TransferDataUtil;
import com.hanhai.material.scheduling.entity.SysProductPeople;
import com.hanhai.material.scheduling.service.SysProductPeopleService;
import com.hanhai.material.utils.jiandaoyun.PushToJianDaoYunUtil;
import com.hanhai.material.utils.redis.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**
 * @author Administrator
 */
@Service
@Log4j2
public class AsyncServiceImpl implements AsyncService {
    @Autowired
    SysProductRecordDetentionRecordService sysProductRecordDetentionRecordService;
    @Autowired
    SysProductRecordDetentionService sysProductRecordDetentionService;

    @Autowired
    SysProductRecordIntoService sysProductRecordIntoService;

    @Autowired
    PushToJianDaoYunUtil pushToJianDaoYunUtil;

    @Autowired
    ProductReceiptUtil productReceiptUtil;

    @Autowired
    TransferDataUtil transferDataUtil;

    /**
     * @param productRecordInto
     * @param countDownLatch
     * @return
     */
    @Override
    public Future<Result<?>> saveProductRecordIntoByAsync(SysProductRecordInto productRecordInto, CountDownLatch countDownLatch) throws IOException {
        if (CollectionUtils.isNotEmpty(productRecordInto.getProductRecordDetentionRecordList())) {
            List<SysProductRecordDetentionRecord> productRecordDetentionRecords = productRecordInto.getProductRecordDetentionRecordList();
            productRecordDetentionRecords.stream().forEach(item -> item.setProductRecordIntoId(productRecordInto.getId()));
            this.sysProductRecordDetentionRecordService.updateBatch(productRecordDetentionRecords);
        }
        String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(productRecordInto);
        productRecordInto.setDataId(dataId);
        this.sysProductRecordIntoService.updateById(productRecordInto);

        countDownLatch.countDown();
        return null;
    }
//    @Override
//    public Future<Result<?>> saveProductRecordIntoByAsync(SysProductRecordInto productRecordInto, CountDownLatch countDownLatch) throws IOException {
//        List<SysProductRecordDetentionRecord> addProductRecordDetentionRecordList = new ArrayList<>();
//        List<SysProductRecordDetentionRecord> updateProductRecordDetentionRecordList = new ArrayList<>();
//        List<SysProductRecordDetentionRecord> sysProductRecordDetentionRecordList = new ArrayList<>();
//        SysProductRecordInto sysProductRecordInto = sysProductRecordIntoService.getMapper().selectOneWithRelationsById(productRecordInto.getId());
//        log.error("Sys添加信息：{}", JSONObject.toJSONString(sysProductRecordInto));
//        LocalDate date = productRecordInto.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//        LocalDate targetDate = LocalDate.of(2024, 3, 31);
////        if (date.isAfter(targetDate)) {
////            this.productReceiptUtil.addAndUpdateProductReceipt(sysProductRecordInto);
////        }
//        if (sysProductRecordInto.getProductRecordDetentionList() != null) {
//            List<SysProductRecordDetention> sysProductRecordDetentionList = sysProductRecordInto.getProductRecordDetentionList();
//
//            for (SysProductRecordDetention sysProductRecordDetention : sysProductRecordDetentionList) {
//                if (sysProductRecordDetention.getNum() > 0) {
//                    sysProductRecordDetention.setStatus(1);
//                } else {
//                    sysProductRecordDetention.setStatus(2);
//                }
//                SysProductRecordDetentionRecord sysProductRecordDetentionRecord = sysProductRecordDetention.getProductRecordDetentionRecord();
//                if (sysProductRecordDetentionRecord != null) {
//                    sysProductRecordDetentionRecordList.add(sysProductRecordDetentionRecord);
//                    if (sysProductRecordDetentionRecord.getNum() > 0) {
//                        sysProductRecordDetentionRecord.setMachineArea(sysProductRecordInto.getMachineArea());
//                        sysProductRecordDetentionRecord.setGroupName(sysProductRecordInto.getGroupName());
//                        sysProductRecordDetentionRecord.setProductRecordIntoId(sysProductRecordInto.getId());
//                        sysProductRecordDetentionRecord.setNowNum(sysProductRecordDetention.getNum());
//                        sysProductRecordDetentionRecord.setProductRecordDetentionId(sysProductRecordDetention.getId());
//                        sysProductRecordDetentionRecord.setShift(sysProductRecordDetention.getShift());
//                        sysProductRecordDetentionRecord.setGoodNum(sysProductRecordInto.getGoodNumPeople());
//                        sysProductRecordDetentionRecord.setBadNum(sysProductRecordInto.getBadNumPeople());
//                        sysProductRecordDetentionRecord.setProductDateInto(sysProductRecordInto.getProductDate());
//                        if (sysProductRecordDetentionRecord.getId() != null) {
//                            updateProductRecordDetentionRecordList.add(sysProductRecordDetentionRecord);
//                        } else {
//                            sysProductRecordDetentionRecord.setId(UUID.randomUUID().toString());
//                            addProductRecordDetentionRecordList.add(sysProductRecordDetentionRecord);
//                        }
//
//                    }
//                }
//            }
//            log.error("sysProductRecordDetentionList:{}", JSONObject.toJSONString(sysProductRecordDetentionList));
//            log.error("updateProductRecordDetentionRecordList:{}", JSONObject.toJSONString(updateProductRecordDetentionRecordList));
//            log.error("addProductRecordDetentionRecordList:{}", JSONObject.toJSONString(addProductRecordDetentionRecordList));
////            if (sysProductRecordDetentionList.size() > 0) {
////                this.sysProductRecordDetentionService.updateBatch(sysProductRecordDetentionList);
////            }
////            if (addProductRecordDetentionRecordList.size() > 0) {
////                this.sysProductRecordDetentionRecordService.saveBatch(addProductRecordDetentionRecordList);
////            }
////            if (updateProductRecordDetentionRecordList.size() > 0) {
////                this.sysProductRecordDetentionRecordService.updateBatch(updateProductRecordDetentionRecordList);
////            }
//
//        }
////        String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(sysProductRecordInto);
////        sysProductRecordInto.setDataId(dataId);
////        this.sysProductRecordIntoService.updateById(sysProductRecordInto);
//
//        countDownLatch.countDown();
//        return null;
//    }

    /**
     * @param productRecordIntoList
     * @param countDownLatch
     * @return
     * @throws IOException
     */
    @Override
    public Future<Result<?>> saveProductRecordIntoByAsyncList(List<SysProductRecordInto> productRecordIntoList, CountDownLatch countDownLatch) throws IOException {
        for (SysProductRecordInto sysProductRecordInto : productRecordIntoList) {
//            if (sysProductRecordInto.getDataId() != null) {
//                try {
//                    this.pushToJianDaoYunUtil.updateToJianDaoYunSingle1(sysProductRecordInto);
//                } catch (Exception e) {
//                    log.error("E:{}", e.getMessage());
//                }
//            } else {
            String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(sysProductRecordInto);
            sysProductRecordInto.setDataId(dataId);
            this.sysProductRecordIntoService.updateById(sysProductRecordInto);
//            }

        }
        countDownLatch.countDown();
        return null;
    }

    /**
     * @param productRecordInto
     * @param countDownLatch
     * @return
     */
    @Override
    public Future<Result<?>> updateProductRecordIntoByAsync(SysProductRecordInto productRecordInto, CountDownLatch countDownLatch) throws IOException {

        if (CollectionUtils.isNotEmpty(productRecordInto.getProductRecordDetentionRecordList())) {
            List<SysProductRecordDetentionRecord> productRecordDetentionRecords = productRecordInto.getProductRecordDetentionRecordList();
            productRecordDetentionRecords.stream().forEach(item -> item.setProductRecordIntoId(productRecordInto.getId()));
            this.sysProductRecordDetentionRecordService.updateBatch(productRecordDetentionRecords);
        }

/*//        if (date.isAfter(targetDate)) {
//            QueryWrapper queryWrapper=QueryWrapper.create();
//            queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION_RECORD.PRODUCT_RECORD_INTO_ID.eq(sysProductRecordInto.getId()));
//            List<SysProductRecordDetentionRecord> sysProductRecordDetentionRecordList1=this.sysProductRecordDetentionRecordService.list(queryWrapper);
//
//            log.error("扣留Data:{}",sysProductRecordDetentionRecordList1);
//            List<TransferModel> transferModelList = this.transferDataUtil.getTransferDataList(sysProductRecordDetentionRecordList1);
//            log.error("Tran:{}", JSONObject.toJSONString(transferModelList));
//            for (TransferModel transferModel : transferModelList) {
//                this.transferDataUtil.addAndUpdateTransferData1(transferModel);
//            }
//        }*/

        if (StringUtils.isNotBlank(productRecordInto.getDataId())) {
            try {
                log.error("更新");
                String dataId = this.pushToJianDaoYunUtil.updateToJianDaoYunSingle1(productRecordInto);
                productRecordInto.setDataId(dataId);
                this.sysProductRecordIntoService.updateById(productRecordInto);
            } catch (Exception e) {
                log.error("添加");
                String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(productRecordInto);
                productRecordInto.setDataId(dataId);
                this.sysProductRecordIntoService.updateById(productRecordInto);
            }
        } else {
            log.error("添加");
            String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(productRecordInto);
            productRecordInto.setDataId(dataId);
            this.sysProductRecordIntoService.updateById(productRecordInto);
        }


        countDownLatch.countDown();
        return null;
    }

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    SysProductPeopleService sysProductPeopleService;

    /**
     * @param productPeopleList
     * @param countDownLatch
     * @return
     */
    @Override
    public Future<Result<?>> saveProductPeopleBatch(List<SysProductPeople> productPeopleList, CountDownLatch countDownLatch) {
        List<SysProductPeople> add = new ArrayList<>();
        List<SysProductPeople> update = new ArrayList<>();
        for (SysProductPeople productPeople : productPeopleList) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String workDate = simpleDateFormat.format(productPeople.getWorkDate());
            log.error("SysProductPeople:" + productPeople);
            String id = workDate + productPeople.getUserId() + productPeople.getWorkTimeIndex().replace("点", "") + productPeople.getMachineName() + productPeople.getWorkPlanId();
            if (redisUtil.hget("scheduling", id) != null) {
                productPeople.setId(id);
                update.add(productPeople);
            } else {
                productPeople.setId(id);
                add.add(productPeople);
            }
        }
        try {
            this.sysProductPeopleService.updateBatch(update);
            this.sysProductPeopleService.saveBatch(add);
        } catch (Exception e) {

        }
        countDownLatch.countDown();
        return null;
    }

    /**
     * @param productPeopleList
     * @param countDownLatch
     * @return
     */
    @Override
    public Future<Result<?>> getHistoryPeople(List<SysProductPeople> productPeopleList, CountDownLatch countDownLatch) {
        List<SysProductPeople> add = new ArrayList<>();
        List<SysProductPeople> update = new ArrayList<>();
        for (SysProductPeople productPeople : productPeopleList) {
            LocalDate workDate = productPeople.getWorkDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDateTime workTime = productPeople.getWorkTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            productPeople.setWorkDate(Date.from(workDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant()));
            productPeople.setWorkTime((Date.from(workTime.plusDays(1).atZone(ZoneId.systemDefault()).toInstant())));

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String workDateS = simpleDateFormat.format(productPeople.getWorkDate());
            log.error("SysProductPeople:" + productPeople);
            String id = workDateS + productPeople.getUserId() + productPeople.getWorkTimeIndex().replace("点", "") + productPeople.getMachineName() + productPeople.getWorkPlanId();
            if (redisUtil.hget("scheduling", id) != null) {
                productPeople.setId(id);
                update.add(productPeople);
            } else {
                productPeople.setId(id);
                add.add(productPeople);
            }
        }
        try {
            this.sysProductPeopleService.updateBatch(update);
            this.sysProductPeopleService.saveBatch(add);
        } catch (Exception e) {

        }
        countDownLatch.countDown();
        return null;
    }

//       @Override
//    public Future<Result<?>> updateProductRecordIntoByAsync(SysProductRecordInto productRecordInto, CountDownLatch countDownLatch) throws IOException {
//
//        List<SysProductRecordDetentionRecord> addProductRecordDetentionRecordList = new ArrayList<>();
//        List<SysProductRecordDetentionRecord> updateProductRecordDetentionRecordList = new ArrayList<>();
//        List<SysProductRecordDetentionRecord> sysProductRecordDetentionRecordList = new ArrayList<>();
//        SysProductRecordInto sysProductRecordInto = sysProductRecordIntoService.getMapper().selectOneWithRelationsById(productRecordInto.getId());
//        log.error("Sys更新信息：{}", JSONObject.toJSONString(sysProductRecordInto));
//
//        LocalDate date = productRecordInto.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//        log.error("ProductDate:{}",productRecordInto.getProductDate());
//        LocalDate targetDate = LocalDate.of(2024, 3, 31);
//        log.error("ISAfter:{}",date.isAfter(targetDate));
////        LocalDate localDate=LocalDate
////        if (date.isAfter(targetDate)) {
////            this.productReceiptUtil.addAndUpdateProductReceipt(sysProductRecordInto);
////        }
//
//        if (productRecordInto.getProductRecordDetentionList() != null) {
//            List<SysProductRecordDetention> sysProductRecordDetentionList = productRecordInto.getProductRecordDetentionList();
//            for (SysProductRecordDetention sysProductRecordDetention : sysProductRecordDetentionList) {
//                if (sysProductRecordDetention.getNum() > 0) {
//                    sysProductRecordDetention.setStatus(1);
//                } else {
//                    sysProductRecordDetention.setStatus(2);
//                }
//                SysProductRecordDetentionRecord sysProductRecordDetentionRecord = sysProductRecordDetention.getProductRecordDetentionRecord();
//                if (sysProductRecordDetentionRecord != null) {
//                    sysProductRecordDetentionRecordList.add(sysProductRecordDetentionRecord);
//                    if (sysProductRecordDetentionRecord.getNum() > 0) {
//                        log.error("SysProductRecord:{}", JSONObject.toJSONString(sysProductRecordDetentionRecord));
//                        sysProductRecordDetentionRecord.setMachineArea(sysProductRecordInto.getMachineArea());
//                        sysProductRecordDetentionRecord.setGroupName(sysProductRecordInto.getGroupName());
//                        sysProductRecordDetentionRecord.setProductRecordIntoId(sysProductRecordInto.getId());
//                        sysProductRecordDetentionRecord.setNowNum(sysProductRecordDetention.getNum());
//                        sysProductRecordDetentionRecord.setProductRecordDetentionId(sysProductRecordDetention.getId());
//                        sysProductRecordDetentionRecord.setShift(sysProductRecordDetention.getShift());
//                        sysProductRecordDetentionRecord.setGoodNum(sysProductRecordInto.getGoodNumPeople());
//                        sysProductRecordDetentionRecord.setBadNum(sysProductRecordInto.getBadNumPeople());
//                        sysProductRecordDetentionRecord.setProductDateInto(sysProductRecordInto.getProductDate());
//                        if (sysProductRecordDetentionRecord.getId() != null) {
//                            updateProductRecordDetentionRecordList.add(sysProductRecordDetentionRecord);
//                        } else {
//                            sysProductRecordDetentionRecord.setId(UUID.randomUUID().toString());
//                            addProductRecordDetentionRecordList.add(sysProductRecordDetentionRecord);
//                        }
//
//                    }
//                }
//            }
//            if (sysProductRecordDetentionList.size() > 0) {
//                this.sysProductRecordDetentionService.updateBatch(sysProductRecordDetentionList);
//
//            }
//            if (addProductRecordDetentionRecordList.size() > 0) {
//                this.sysProductRecordDetentionRecordService.saveBatch(addProductRecordDetentionRecordList);
//
//            }
//            if (updateProductRecordDetentionRecordList.size() > 0) {
//                this.sysProductRecordDetentionRecordService.updateBatch(updateProductRecordDetentionRecordList);
//            }
//        }
////        if (date.isAfter(targetDate)) {
////            QueryWrapper queryWrapper=QueryWrapper.create();
////            queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION_RECORD.PRODUCT_RECORD_INTO_ID.eq(sysProductRecordInto.getId()));
////            List<SysProductRecordDetentionRecord> sysProductRecordDetentionRecordList1=this.sysProductRecordDetentionRecordService.list(queryWrapper);
////
////            log.error("扣留Data:{}",sysProductRecordDetentionRecordList1);
////            List<TransferModel> transferModelList = this.transferDataUtil.getTransferDataList(sysProductRecordDetentionRecordList1);
////            log.error("Tran:{}", JSONObject.toJSONString(transferModelList));
////            for (TransferModel transferModel : transferModelList) {
////                this.transferDataUtil.addAndUpdateTransferData1(transferModel);
////            }
////        }
//        if (sysProductRecordInto.getDataId() != null) {
//            try {
//                log.error("更新");
//                String dataId = this.pushToJianDaoYunUtil.updateToJianDaoYunSingle1(sysProductRecordInto);
//                sysProductRecordInto.setDataId(dataId);
//                this.sysProductRecordIntoService.updateById(sysProductRecordInto);
//            } catch (Exception e) {
//                log.error("添加");
//                String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(sysProductRecordInto);
//                sysProductRecordInto.setDataId(dataId);
//                this.sysProductRecordIntoService.updateById(sysProductRecordInto);
//            }
//        } else {
//            log.error("添加");
//            String dataId = this.pushToJianDaoYunUtil.pushToJianDaoYunSingle1(sysProductRecordInto);
//            sysProductRecordInto.setDataId(dataId);
//            this.sysProductRecordIntoService.updateById(sysProductRecordInto);
//        }
//
//
//        countDownLatch.countDown();
//        return null;
//    }
//
//
}
